<template>
    <header class="header">
        <FanPageHeader
          :subTitle="articleStore.subTitle"
          current="返回博客"
          :img="getBackendImageUrl(articleStore.img)"
          :title="articleStore.title"
        />
        <!-- Waves 放在header内部，覆盖在图片下部分 -->
        <div class="waves-wrapper">
          <Waves height="6rem" />
        </div>
      </header>

      <main class="main">
        <!-- 桌面端布局 -->
        <div class="desktop-layout" v-if="!isMobile()">
          <a-col :span="14" offset="2">
            <!-- TODO ：增加文章区域的边幅 以及卡片样式 -->
            <div class="markdown-body" v-html="content" />
          </a-col>
          <a-col :span="7" offset="1">
            <!-- 目录（锚点） -->
            <a-card title="文章目录" class="toc-card">
              <div class="toc-container">
                <div 
                  v-for="item in toc" 
                  :key="item.id"
                  class="toc-item"
                  :data-toc-id="item.id"
                  :style="{ paddingLeft: (item.level - 1) * 16 + 'px' }"
                  @click="scrollToHeading(item.id)"
                >
                  <a-button type="link" size="small">
                    {{ item.text }}
                  </a-button>
                </div>
                <div v-if="toc.length === 0" class="toc-empty">
                  暂无目录
                </div>
              </div>
            </a-card>
          </a-col>
        </div>
        
        <!-- 移动端布局 -->
        <div class="mobile-layout" v-if="isMobile()">
          <!-- 目录卡片 -->
          <div class="mobile-toc-wrapper">
            <a-card title="文章目录" class="mobile-toc-card">
              <!-- 移动端目录切换按钮 -->
              <div class="toc-toggle" @click="tocVisible = !tocVisible">
                <span>{{ tocVisible ? '收起目录' : '展开目录' }}</span>
                <span class="toc-toggle-icon">{{ tocVisible ? '▲' : '▼' }}</span>
              </div>
              <div class="toc-container" :class="{ 'toc-mobile-hidden': !tocVisible }">
                <div 
                  v-for="item in toc" 
                  :key="item.id"
                  class="toc-item"
                  :data-toc-id="item.id"
                  :style="{ paddingLeft: (item.level - 1) * 16 + 'px' }"
                  @click="scrollToHeading(item.id)"
                >
                  <a-button type="link" size="small">
                    {{ item.text }}
                  </a-button>
                </div>
                <div v-if="toc.length === 0" class="toc-empty">
                  暂无目录
                </div>
              </div>
            </a-card>
          </div>
          
          <!-- 文章内容 -->
          <div class="mobile-content-wrapper">
            <div class="markdown-body" v-html="content" />
          </div>
        </div>
      </main>
</template>

<script setup>
// const props = defineProps({
//     id: {
//         type: Number,
//         default: 1
//     }
// })
import md from '../../utils/md.js';
const content  = ref('')
const toc = ref([]) // 目录数据
const tocVisible = ref(false) // 移动端目录显示状态
import { FanNotification } from '../../libs/util.toast';
import { ref, onMounted, nextTick } from 'vue'
import FanPageHeader from '../../components/common/FanPageHeader.vue';
import Waves from '../../components/common/Waves.vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const articleID = route.params.id;
import { useArticleStore } from '../../stores/article';
const articleStore = useArticleStore();
import { getBackendImageUrl } from '../../libs/util.common.js';
// 生成目录函数
const generateTOC = () => {
  // 只在目录为空时生成，避免重复
  if (toc.value.length > 0) {
    return;
  }
  
  const headings = document.querySelectorAll('.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6');
  toc.value = Array.from(headings).map((heading, index) => {
    const id = heading.id || `heading-${index}`;
    if (!heading.id) {
      heading.id = id; // 确保每个标题都有 ID
    }
    return {
      id: id,
      text: heading.textContent,
      level: parseInt(heading.tagName.charAt(1)),
      element: heading
    };
  });
};

// 滚动到指定标题
const scrollToHeading = (id) => {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    // 移除之前的高亮
    document.querySelectorAll('.toc-item.active').forEach(item => {
      item.classList.remove('active');
    });
    // 添加当前高亮
    const tocItem = document.querySelector(`[data-toc-id="${id}"]`);
    if (tocItem) {
      tocItem.classList.add('active');
    }
    // 移动端点击后自动收起目录
    if (window.innerWidth <= 768) {
      tocVisible.value = false;
    }
  }
};

// 检测是否为移动端
const isMobile = () => window.innerWidth <= 768;

const getDetail = async () => {
    const res = await articleStore.getArticleDetail(articleID);
    if (res.success) {
      content.value = md.render(res.data.content);
      // 等待 DOM 更新后生成目录
      await nextTick();
      generateTOC();
    }
    else {
        FanNotification.error('获取文章详情失败');
    }
}

onMounted(async () => {
  await getDetail();
  // 增加观看量
 await articleStore.addViews(articleID);
  
  // 初始化时判断设备类型
  if (isMobile()) {
    tocVisible.value = false;
  }
  
  // 监听滚动事件，自动高亮当前标题
  window.addEventListener('scroll', () => {
    const headings = document.querySelectorAll('.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6');
    let currentHeading = null;
    
    headings.forEach(heading => {
      const rect = heading.getBoundingClientRect();
      if (rect.top <= 100 && rect.bottom > 100) {
        currentHeading = heading.id;
      }
    });
    
    if (currentHeading) {
      document.querySelectorAll('.toc-item').forEach(item => {
        item.classList.remove('active');
      });
      const currentTocItem = document.querySelector(`[data-toc-id="${currentHeading}"]`);
      if (currentTocItem) {
        currentTocItem.classList.add('active');
      }
    }
  });
  
  // 监听窗口大小变化，处理响应式布局变化
  window.addEventListener('resize', () => {
    // 当从小屏切换到大屏时，重置移动端目录状态
    if (window.innerWidth > 768) {
      tocVisible.value = false;
    }
  });
});
</script>

<style scoped lang="scss">
/* 页面整体布局 */
.page {
    min-height: 100vh;
  
  }
  .header {
    position: relative;
    width: 100%;
    flex-shrink: 0;
  }
  
  /* 移动端优化 */
  @media (max-width: 768px) {
    .header {
      margin-bottom: 16px;
    }
    
    .waves-wrapper {
      height: 6rem;
    }
  }
  .main {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    align-items: flex-start; /* 确保顶部对齐 */
  }
  
  /* 桌面端布局 */
  .desktop-layout {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  
  .mobile-layout {
    display: none;
  }
  
  .toc-card {
    position: sticky;
    top: 20px;
  }
  /* Waves 包装器 - 确保波浪只覆盖图片下部分 */
  .waves-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 10rem;
    pointer-events: none; /* 确保不拦截鼠标事件 */
  }
  /* 代码块横向滚动 */
.markdown-body pre.hljs { overflow-x: auto; padding: 16px; }

/* 标题锚点样式 */
.header-anchor {
  display: none; /* 移动端隐藏锚点符号 */
}

@media (min-width: 769px) {
  .header-anchor {
    opacity: 0;
    transition: opacity 0.2s ease;
    text-decoration: none;
    margin-left: 8px;
    display: inline-block;
  }
}
/* 响应式布局 */
@media (max-width: 768px) {
  .desktop-layout {
    display: none;
  }
  
  .mobile-layout {
    display: block;
    padding: 0 16px;
  }
  
  .mobile-toc-wrapper {
    margin-bottom: 16px;
  }
  
  .mobile-content-wrapper {
    margin-top: 16px;
  }
  
  .toc-container {
    max-height: 250px;
  }
  
  .toc-item .ant-btn-link {
    font-size: 14px;
    padding: 6px 8px;
  }
  
  .markdown-body {
    padding: 16px;
    font-size: 15px;
    line-height: 1.6;
  }
  
  .markdown-body h1, .markdown-body h2, .markdown-body h3 {
    font-size: 18px;
    margin: 16px 0 12px;
  }
  
  .markdown-body pre.hljs {
    font-size: 13px;
    padding: 12px;
    margin: 12px -16px;
  }
  
  .markdown-body img {
    max-width: 100%;
    height: auto;
  }
}
  /* 目录样式 */
  .toc-container {
    max-height: 70vh;
    overflow-y: auto;
    padding: 8px 0;
  }
  
  .toc-empty {
    text-align: center;
    color: #999;
    padding: 20px;
    font-size: 14px;
  }
  
  /* 移动端目录切换 */
  .toc-toggle {
    display: none;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    font-size: 14px;
    color: #1890ff;
    margin-bottom: 8px;
  }
  
  .toc-toggle-icon {
    font-size: 12px;
    transition: transform 0.2s;
  }
  
  @media (max-width: 768px) {
    .toc-toggle {
      display: flex;
    }
    
    .toc-container.toc-mobile-hidden {
      display: none;
    }
    
    .toc-container {
      max-height: 50vh;
      border-top: 1px solid #f0f0f0;
      margin-top: 8px;
    }
  }
  
  .toc-item {
    margin: 4px 0;
    transition: all 0.2s ease;
  }
  
  .toc-item:hover {
    background-color: #f5f5f5;
    border-radius: 4px;
  }
  
  .toc-item.active {
    background-color: #e6f7ff;
    border-left: 3px solid #1890ff;
    border-radius: 4px;
  }
  
  .toc-item .ant-btn-link {
    color: #333;
    text-align: left;
    padding: 4px 8px;
    height: auto;
    line-height: 1.4;
    white-space: normal;
    word-break: break-word;
  }
  
  .toc-item .ant-btn-link:hover {
    color: #1890ff;
  }
  
  .toc-empty {
    text-align: center;
    color: #999;
    padding: 20px;
  }
</style>